<template>
  <div class="user_group">
    <Resize>
      <template v-slot:left>
        <div class="content_l">
          <div class="left-btn">
            <vxe-toolbar v-if="false">
              <template #buttons>
                <vxe-button @click="$refs.xTree.setAllTreeExpand(true)"
                  >全部展开</vxe-button
                >
                <vxe-button @click="$refs.xTree.clearTreeExpand()"
                  >全部关闭</vxe-button
                >
                <vxe-button @click="getSiteList" v-if="siteRow"
                  >返回站点</vxe-button
                >
                <!-- <vxe-button @click="getSiteList">返回站点</vxe-button> -->
              </template>
            </vxe-toolbar>
            <vxe-toolbar>
              <template #buttons>
                <vxe-button
                  size="mini"
                  @click="getSiteList"
                  :disabled="!siteRow"
                  >返回站点</vxe-button
                >
                <!-- <vxe-button @click="getSiteList">返回站点</vxe-button> -->
              </template>
            </vxe-toolbar>
          </div>
          <vxe-table
            highlight-current-row
            highlight-hover-row
            row-key
            :show-header="false"
            show-overflow
            ref="xTree"
            border="inner"
            :data="siteList"
            :tree-config="{
              children: 'children',
              transform: false,
              parentKey: 'parentId',
              line: true,
              iconOpen: 'el-icon-remove',
              iconClose: 'el-icon-circle-plus',
            }"
            @current-change="clickListRow"
            class="left-table"
          >
            <vxe-column tree-node show-overflow>
              <template #default="{ row }">
                <span>
                  <span
                    v-if="
                      (row.groupId || row.siteId || row.net) == currentRowId &&
                      !row.root
                    "
                    class="activeRow"
                  >
                    <svg-icon icon-class="right" style="color: #009a94" />
                  </span>
                  <!-- 电脑 -->
                  <img
                    src="../../../assets/icons/png/Display Check.png"
                    alt=""
                    style="vertical-align: text-bottom"
                    v-if="row.root == '000'"
                  />
                  <!-- 地球 -->
                  <img
                    src="../../../assets/icons/png/globe.gif"
                    alt=""
                    style="vertical-align: bottom"
                    v-if="!row.groupName && row.root != '000'"
                  />

                  <img
                    src="../../../assets/icons/png/role.gif"
                    alt=""
                    style="vertical-align: text-bottom"
                    v-if="row.groupName"
                  />

                  <img
                    src="../../../assets/icons/png/contextMenu.gif"
                    alt=""
                    @click.stop="openMenu(row, $event)"
                    v-if="row.root == '111'"
                  />

                  <!-- <i class="tree-node-icon fa" :class="$refs.xTree.isTreeExpandByRow(row) ? 'el-icon-folder-opened' : 'el-icon-folder'"></i> -->

                  <span style="cursor: pointer; fontsize: 12px; color: #000">
                    {{ row.name || row.groupName }}</span
                  >
                </span>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </template>
      <template v-slot:right>
        <div class="content_r">
          <el-row :gutter="10" class="mb8 grid-content" v-if="siteRow">
            <el-col :span="1.5" v-if="!userGroupRow">
              <el-button
                type="primary"
                plain
                icon="el-icon-add"
                size="mini"
                v-hasPermi="['system:group:add']"
                @click="handleAdd"
                >新增</el-button
              >
            </el-col>
            <el-col :span="1.5" v-if="userGroupRow">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                v-hasPermi="['system:group:edit']"
                @click="handleUpdate"
                >修改</el-button
              >
            </el-col>
            <el-col :span="1.5" v-if="userGroupRow">
              <el-button
                type="primary"
                plain
                icon="el-icon-delete"
                size="mini"
                v-hasPermi="['system:group:del']"
                @click="handleDel"
                >删除</el-button
              >
            </el-col>
          </el-row>
          <template v-if="userGroupRow">
            <el-tabs
              type="border-card"
              v-model="userGroupTabsValue"
              @tab-click="handleTabClick"
            >
              <el-tab-pane
                label="用户组_用户"
                name="one"
                :lazy="true"
                v-hasPermi="['system:privileg:save', 'system:privileg:delete']"
              >
                <One ref="user" v-if="userGroupTabsValue == 'one'"></One>
              </el-tab-pane>
              <el-tab-pane
                label="系统菜单权限"
                name="two"
                :lazy="true"
                v-hasPermi="['system:privileg:save', 'system:privileg:delete']"
              >
                <Two
                  v-if="userGroupTabsValue == 'two'"
                  :SysSubMenu="groupPrivilege.SysSubMenu"
                  @getGroupInitPrivilege="getGroupInitPrivilege"
                ></Two>
              </el-tab-pane>
              <el-tab-pane
                label="文章及栏目权限 "
                name="three"
                :lazy="true"
                v-hasPermi="['system:privileg:save', 'system:privileg:delete']"
              >
                <Three
                  v-if="userGroupTabsValue == 'three'"
                  :WebSite="groupPrivilege.WebSite"
                  :Channel="groupPrivilege.Channel"
                  @getGroupInitPrivilege="getGroupInitPrivilege"
                ></Three>
              </el-tab-pane>
              <el-tab-pane
                label="共享模板权限"
                name="four"
                :lazy="true"
                v-hasPermi="['system:privileg:save', 'system:privileg:delete']"
              >
                <Four
                  v-if="userGroupTabsValue == 'four'"
                  :TemplateFolder="groupPrivilege.TemplateFolder"
                  :TemplateWebSite="groupPrivilege.TemplateWebSite"
                  @getGroupInitPrivilege="getGroupInitPrivilege"
                ></Four>
              </el-tab-pane>
            </el-tabs>
          </template>
        </div>
      </template>
    </Resize>

    <ul
      v-show="visible"
      :style="{ left: left + 'px', top: top + 'px' }"
      class="contextmenu"
    >
      <li @click="handleAdd">新建用户组</li>
    </ul>
    <el-dialog
      v-dialogDrag
      :title="title"
      :visible.sync="dialogGroup"
      width="30%"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="bottom">
        <el-form
          ref="form"
          :model="formGroup"
          :rules="userGroupRules"
          label-width="120px"
        >
          <el-form-item label="用户组名称" prop="groupName">
            <el-input
              v-model="formGroup.groupName"
              maxlength="50"
              clearable
              placeholder="请输入用户组名称"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="groupDesc" placeholder="描述">
            <el-input v-model="formGroup.groupDesc"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="gropuSureAdd">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { editsite, addSite, listSite, publicSite } from "@/api/content/net";
import { getChannelListForTree, publicChannel } from "@/api/content/clounm";
import {
  GroupList,
  GroupUserList,
  addGroup,
  groupDetail,
  delGroup,
  editGroup,
  initializePrivilege,
} from "@/api/system/userGroup";
import { objectMerge } from "@/utils/index";
import One from "./components/One";
import Two from "./components/Two";
import Three from "./components/Three";
import Four from "./components/Four";
import { mapState } from "vuex";
import auth from "@/plugins/auth";
export default {
  name: "userGroup",
  props: {},
  data() {
    return {
      visible: false,
      top: 0,
      left: 0,
      a: 0,
      userGroupTabsValue: "one",
      //对话框
      dialogGroup: false,
      title: "",
      //用户组详情表单
      formGroup: {},
      //左侧站点列表
      siteList: [],
      //站点行
      siteRow: {},
      //用户组行
      userGroupRow: {},
      //用户组已有的权限
      groupPrivilege: {},
      userGroupRules: {
        groupName: [
          { required: true, message: "用户组名称不能为空", trigger: "blur" },
        ],
      },
    };
  },

  components: { Four, Three, Two, One },

  computed: {
    ...mapState({
      roles: (state) => state.user.roles,
    }),
    currentRowId() {
      return this.userGroupRow?.groupId || this.siteRow?.siteId;
    },
  },
  created() {
    this.getSiteList();
  },
  mounted() {},

  watch: {
    visible(value) {
      if (value) {
        document.body.addEventListener("click", this.closeMenu);
      } else {
        document.body.removeEventListener("click", this.closeMenu);
      }
    },
  },

  methods: {
    //获取站点列表
    getSiteList() {
      this.siteRow = null;
      this.userGroupRow = null;
      listSite()
        .then((res) => {
          if (auth.hasRoleOr(["admin", "wz-admin"])) {
            res.data.unshift({
              siteId: this.CONSTANCE.siteId,
              name: "平台系统",
            });
            this.siteList = [
              { name: "用户组管理-站点列表", root: "000", children: res.data },
            ];
          }
        })

        .then(() => {
          //展开第一个节点
          this.$nextTick(() => {
            this.$refs.xTree.setTreeExpand(this.siteList[0], true);
          });
        });
    },

    //获取栏目列表
    clickListRow({ row }) {
      console.log("row: ", row);
      if (row.root == "000") {
        return;
      }
      this.userGroupTabsValue = "";

      this.$refs.xTree.setCurrentRow(row);
      this.$nextTick(() => {
        if (row.groupId) {
          this.$store.dispatch("column/setUserGroupRow", row);

          //点击用户组行  展示用户tab
          this.userGroupRow = row;
          this.haldleClickGroupRow();
        } else if (row.root == "000") {
          // 点击主站行
          this.a = 0;

          this.siteRow = null;
          this.userGroupRow = null;

          this.$store.dispatch("column/setSiteRow", null);
          this.$store.dispatch("column/setUserGroupRow", null);
        } else if (row.root == "111") {
          // 点击主站行
          this.a = 0;
          this.userGroupRow = null;
        } else {
          //点击站点行    获取栏目列表
          this.siteRow = row;
          this.userGroupRow = null;
          this.$store.dispatch("column/setUserGroupRow", null);

          this.$store.dispatch("column/setSiteRow", row);
          this.haldleClickSite();
        }
      });
    },
    //点击用户组行
    haldleClickGroupRow() {
      console.log("haldleClickGroupRow: ");

      this.a = 1;
      this.userGroupTabsValue = "one";
      this.getGroupInitPrivilege(true);
      // GroupUserList({
      //   siteId: this.siteRow.siteId,
      //   groupId: this.userGroupRow.groupId,
      // }).then((res) => {
      // });
    },
    //获取当前用户组已经拥有的权限
    getGroupInitPrivilege(flag) {
      initializePrivilege({ groupId: this.userGroupRow.groupId })
        .then((res) => {
          let arr = res.data.reduce((acc, item) => {
            if (acc[item.functionType]) {
              acc[item.functionType].push(item);
            } else {
              acc[item.functionType] = [item];
            }
            return acc;
          }, {});
          console.log("已有权限进行分类后", arr);

          let SysSubMenu = [];
          let TemplateFolder = [];
          let TemplateWebSite = [];
          let WebSite = [];
          let Channel = [];
          res.data.forEach((item) => {
            if (
              item.functionType == "SysSubMenu" ||
              item.functionType == "SysMainMenu"
            ) {
              SysSubMenu.push(item);
            } else if (item.functionType == "TemplateFolder") {
              TemplateFolder.push(item);
            } else if (item.functionType == "TemplateWebSite") {
              TemplateWebSite.push(item);
            } else if (item.functionType == "WebSite") {
              WebSite.push(item);
            } else if (item.functionType == "Channel") {
              Channel.push(item);
            }
          });
          this.groupPrivilege = {
            SysSubMenu,
            TemplateFolder,
            TemplateWebSite,
            WebSite,
            Channel,
          };
        })
        .then(() => {
          if (flag) {
            this.$nextTick(() => {
              this.$refs.user.haldleClickColumn();
            });
          }
        });
    },
    //点击站点  获取站点用户组
    haldleClickSite() {
      GroupList({ siteId: this.siteRow.siteId })
        .then((res) => {
          this.siteRow.children = res.data;
          this.siteRow.root = "111";
          this.siteList = [this.siteRow];
        })
        .then(() => {
          //展开第一个节点
          this.$nextTick(() => {
            this.$refs.xTree.setTreeExpand(this.siteList[0], true);
          });
        });
    },
    handleTabClick(tab, e) {
      if (this.userGroupTabsValue == "one") {
        this.$nextTick(() => {
          this.$refs.user.haldleClickColumn();
        });
      }
    },
    gropuSureAdd() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.formGroup.siteId != undefined) {
            editGroup(this.formGroup).then((res) => {
              this.msgSuccess("修改成功");
              this.dialogGroup = false;
              this.haldleClickSite();
            });
          } else {
            addGroup(
              objectMerge(this.formGroup, { siteId: this.siteRow.siteId })
            ).then((res) => {
              this.msgSuccess("添加成功");
              this.dialogGroup = false;
              this.haldleClickSite();
            });
          }
        }
      });
    },
    cancel() {
      this.dialogGroup = false;
      this.reset();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.dialogGroup = true;
      this.title = "添加用户组";
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset();
      groupDetail({ groupId: this.userGroupRow.groupId }).then((res) => {
        this.formGroup = res.data;
        this.title = "修改用户组";
        this.dialogGroup = true;
      });
    },
    //删除用户组
    handleDel() {
      const userGroupRow = this.userGroupRow;

      this.$confirm(
        '是否确认删除用户组"' + userGroupRow.groupName + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          return delGroup({ groupId: userGroupRow.groupId });
        })
        .then(() => {
          this.haldleClickSite();
          this.userGroupRow = null;
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 表单重置
    reset() {
      this.formGroup = {
        groupName: undefined,
        groupDesc: undefined,
        siteId: undefined,
        groupId: undefined,
      };
      this.resetForm("form");
    },
    openMenu(row, e) {
      const menuMinWidth = 105;
      const offsetLeft = this.$el.getBoundingClientRect().left; // container margin left
      const offsetWidth = this.$el.offsetWidth; // container width
      const maxLeft = offsetWidth - menuMinWidth; // left boundary
      const left = e.clientX + 15; // 15: margin right
      if (left > maxLeft) {
        this.left = maxLeft;
      } else {
        this.left = left;
      }
      this.top = e.clientY + 15;
      this.visible = true;
    },
    closeMenu() {
      this.visible = false;
    },
  },
};
</script>

<style scoped lang="scss">
.user_group {
  display: flex;
  flex-direction: row;
  border: 1px solid #ccc;
  .content_l {
    overflow: auto;
    // min-width: 240px;
    width: 100%;
    height: 100%;
    background: #f4f4f4 !important;
    display: flex;
    flex-direction: column;
    .left-table {
      flex: 1;
      height: 0;
      overflow: overlay;
      overflow: auto;
      min-width: 240px;
    }
  }
  .content_r {
    overflow: overlay;
    overflow: auto;
    width: 100%;
    // padding: 10px;
    border-left: 1px solid #ccc;
    height: 100%;
    flex: 1;
    display: flex;
    flex-direction: column;
    ::v-deep .el-tabs {
      flex: 1;
      height: 0; ///////////
      .el-tabs__content {
        height: calc(100% - 60px);
        overflow: auto;
        .el-tab-pane {
          height: 100%;
        }
      }
    }
  }
}
</style>
